package com.cy;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLDecoder;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.*;

@Slf4j
public class DemoUtil {

	//开发/测试环境
	private static String appId="6e3bd7f1999ca1c32889669bf476f1da";//合作渠道id
	private static String source="01";//合作渠道类型 01:内容转接系统 02:拉新系统
	private static String aesTokenKey="26e90e893d8fcb92";//token验证aeskey
	/**获取用户信息 请求之密钥*/
	private static String prikey="MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAIjyI4xJiWXA3Q9JHdRRZTZV6MRxItFdHZ550rBhuj+cQtfwQhKhIarVbJLbdMQ1PKrc0hd5do8ESssFGE57WpZpebpneweIiVD0xyfEw6hwqz+bflGdHHUdNnC7gJ60rb5i29WYbXKBe/r0LNX+W0v90gA90nle/7Aixp6u2/rhAgMBAAECgYBs/TjpZ4UgJFRK3AgPeBAzJEAyR1BMi+0MuSvDEKQoB/by4NXU+cRPr7fPUTUnCq+T1FaoNBT1UZcs6IsluuqmaMqZDGyDwgDzmyvN1h56O/FZvlrWxUCwC16fza0dPsoCzCYTl6CaJAqIYBRSSBbkW48CEafg87z88cl6yEFFoQJBANub7f7mbp9ivkMr088RABo0oTS/nmsmJEIG+miauEqeOxGfu3qLKCNmDw5HNZPDoaENIqw22/6nfuoTtW9b/z0CQQCfo4oTF5rpJa6AuW4Auto7aV5F0W8PQRmek3wdLbi6xiraD23e/+XOT/kjIztsikYYoI6GQq0EAKqixaNMVuR1AkEAqaFSPnhDrn2ZNU1fOCyLhbJtas8wUNePXikBt1b7TzfVrJFTQR7IDD/DFWZPrimIaVw6Egf1+kfqsmgy1yeaiQJAD/eQiOZUhTtSn+dsHECUMVsRpdQT0qfFQzonMNfw4SWPBa6DY8mel6siFSSh/fI6np34g29J1NuoNY2lDq6mPQJAaAVNyJ6Ki2LVHCEMHsudi+CfFPFotZ1WuuffFtpul+Q3FC20atA8w9gpPGPD2IEPOAIlpnLYcb/UvNjNjvuAPQ==";
	/**获取用户信息 返回数据之验签密钥*/
	private static String pubkey="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCAFXUkK5YG5u97P1/7Mvth8zsexfYAA1vRIOPLGPap4S5N+r0VJb6paE+svX178QeSUIuV5U3c02h6ouWaNnhqO3/qAXIfe/0DOaWo/Onf/Us3hdMsEe8JpBCQo5iilV6uU61iYZljDpgWgI+tDS9HHXO/Eo65zgYCqoziDZktqQIDAQAB";
	/**获取用户信息 返回数据之敏感信息密钥*/
	public static String originKey="31349862bfa473deba8ea973b";

	private static final String DES = "DESede";

	public static boolean validateToken(String appId, String token, String aesTokenKey) {
//        String encryptToken = AESUtils.aesDecrypt(token, aesTokenKey);
//        if (StringUtils.isBlank(encryptToken)) {
//            return false;
//        }
//        String appIdEncry = encryptToken.substring(2, 12)
//            + encryptToken.substring(encryptToken.length() - 22, encryptToken.length());
//        StringBuffer sbFront = new StringBuffer(appIdEncry);
//        String sbRev = sbFront.reverse().toString();
//        if (appId.equals(sbRev)) {
//            return true;
//        }
        return false;
    }
	/**
	 *
	 * @param unionTok token值
	 * @param source 来源渠道标识
	 * @param reqType 获取数据类型1 获取所有参数 2.手机号+姓名
	 * @return
	 */
	public static JSONObject getUnionInfo(String unionTok,String source,int reqType) {
		JSONObject retObj=new JSONObject();
		retObj.put("source", source);
		retObj.put("unionTok", unionTok);
		retObj.put("timestamp", System.currentTimeMillis());
		retObj.put("nonceStr", createNonceStr());
		try {
			retObj.put("reqStatus", reqType);
			Map<String, String> params = JSONObject.parseObject(retObj.toJSONString(),
					new TypeReference<Map<String, String>>() {
					});
			retObj.put("signature", sign(sortMap(params), getPrivateKey(prikey)));
			return retObj;
		} catch (Exception e) {
			log.error("加解密出现异常:",e);
		}
		return null;
	}
	/**
	 * 签名有效性验证
	 *
	 * @param
	 * @return
	 */
	public static boolean validateSignStr(JSONObject jsonObj,PublicKey pubKey) {
		String signOrg=jsonObj.getString("signature");
		jsonObj.remove("signature");
		Map<String, String> params = JSONObject.parseObject(jsonObj.toJSONString(),
				new TypeReference<Map<String, String>>() {
				});
		try {
		       byte[] keyBytes = pubKey.getEncoded();
		        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
		        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
		        PublicKey key = keyFactory.generatePublic(keySpec);
		        Signature signature = Signature.getInstance("SHA256WithRSA");
		        signature.initVerify(key);
		        signature.update(sortMap(params).getBytes());
		        return signature.verify(Base64.decodeBase64(signOrg.getBytes()));
		} catch (Exception e) {
			log.error("签名有效性验证出现异常:", e);
		}
		return false;
	}
	public static String sortMap(Map<String, String> param) {
		if (param == null || param.size() == 0) {
			return "";
		}
		StringBuilder result = new StringBuilder();
		Collection<String> keySet = param.keySet();
		List<String> list = new ArrayList<String>(keySet);
		Collections.sort(list);
		for (int i = 0; i < list.size(); ++i) {
			String key = list.get(i);
			result.append(key).append("=").append(param.get(key)).append("&");
		}
		return result.substring(0, result.length() - 1);
	}

	/**
	 * 数据解密
	 * @param cipherText
	 * @param originKey
	 * @return
	 * @throws Exception
	 */
	public static String desDecript(String cipherText, String originKey) throws Exception {
		Cipher cipher = Cipher.getInstance(DES); /* 初始化加密方式 */
		Key key = getKey(originKey); /* 获取密钥 */
		cipher.init(Cipher.DECRYPT_MODE, key); /* 初始化操作方式 */
		byte[] decode = Base64.decodeBase64(cipherText); /* 按照Base64解码 */
		byte[] doFinal = cipher.doFinal(decode); /* 执行解码操作 */
		return new String(doFinal); /* 转换成相应字符串并返回 */
	}

	/**
	 * 获取密钥算法
	 *
	 * @param originKey
	 * @return
	 */
	private static SecretKeySpec getKey(String originKey) {
		byte[] buffer = new byte[24];
		byte[] originBytes = originKey.getBytes();
		/**
		 * 防止输入的密钥长度超过192位
		 */
		for (int i = 0; i < 24 && i < originBytes.length; i++) {
			buffer[i] = originBytes[i]; /* 如果originBytes不足8,buffer剩余的补零 */
		}
		SecretKeySpec key = new SecretKeySpec(buffer, DES); /*密钥字节数组,加密方式 */
		return key;
	}
    /**
     * 获取公钥
     *
     * @param publicKey 公钥字符串
     * @return
     */
    public static PublicKey getPublicKey(String publicKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.decodeBase64(publicKey.getBytes());
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodedKey);
        return keyFactory.generatePublic(keySpec);
    }
	public static String createNonceStr() {
		String sl = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		StringBuilder sb = new StringBuilder();
		for (int i = 0; i < 16; i++) {
			sb.append(sl.charAt(new Random().nextInt(sl.length())));
		}
		return sb.toString();
	}
    /**
     * 获取私钥
     *
     * @param privateKey 私钥字符串
     * @return
     */
    public static PrivateKey getPrivateKey(String privateKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodedKey = Base64.decodeBase64(privateKey.getBytes());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodedKey);
        return keyFactory.generatePrivate(keySpec);
    }
	public static String sign(String value, PrivateKey signKey)
			throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException {
//		byte[] keyBytes = Base64.decodeBase64(signKey);
		byte[] keyBytes = signKey.getEncoded();
		PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyf = KeyFactory.getInstance("RSA");
		PrivateKey pk = keyf.generatePrivate(keySpec);
		Signature signature = Signature.getInstance("SHA256WithRSA");
		signature.initSign(pk);
		signature.update(value.getBytes());
		String sign = Base64.encodeBase64String(signature.sign());
		return sign;
	}
	 /**
     * aes解密
     * @param encrypt   内容
     * @return
     * @throws Exception
     */
    public static String aesDecrypt(String encrypt,String KEY) {
        try {
            return aesDecryptRenew(encrypt, KEY);
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }
	/**
	 * 将base 64 code AES解密
	 * @param encryptStr 待解密的base 64 code
	 * @param decryptKey 解密密钥
	 * @return 解密后的string
	 * @throws Exception
	 */
	public static String aesDecryptRenew(String encryptStr, String decryptKey) throws Exception {
		return StringUtils.isEmpty(encryptStr) ? null : aesDecryptByBytes(base64Decode(encryptStr), decryptKey);
	}
	/**
	 * base 64 decode
	 * @param base64Code 待解码的base 64 code
	 * @return 解码后的byte[]
	 * @throws Exception
	 */
	public static byte[] base64Decode(String base64Code){
		return StringUtils.isEmpty(base64Code) ? null : Base64.decodeBase64(base64Code);
	}
	/**
	 * AES解密
	 * @param encryptBytes 待解密的byte[]
	 * @param decryptKey 解密密钥
	 * @return 解密后的String
	 * @throws Exception
	 */
	 public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {
	        KeyGenerator kgen = KeyGenerator.getInstance("AES");
	        kgen.init(128);

	        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
	        cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
	        byte[] decryptBytes = cipher.doFinal(encryptBytes);

	        return new String(decryptBytes);
	    }
}
